import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProForm, { DrawerForm, ProFormText, ModalForm, ProFormUploadDragger, ProFormSelect } from '@ant-design/pro-form';
import React, { useState, useRef } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { teamList,saveTeam,updateTeam,deleteTeam,lineList,deptList,getDetailsByTeamId ,authTeam} from '../service';
import { Popconfirm,Button,message, Form, Select } from 'antd';
import { FileExcelOutlined } from '@ant-design/icons';
import { manufacturerOptionOnly } from '@/utils/utils';
const { Option } = Select;
export default () => {
const [showCreate, setShowCreate] = useState(false);
const actionRef = useRef<ActionType>();
const [detail, setDetail] = useState<any>({});
const [showImport, setShowImport] = useState<boolean>(false);
const [showAuth,setShowAuth] = useState<boolean>(false);
const [productLines, setProductLines] = useState<any>([]);
const [productLine,setProductLine] = useState<any>({});
const [pData,setPdata] = useState<any>([]);
const [depts,setDepts] = useState<any>([]);
const pColumns :ProColumns[] = [
  {
    title: '产品名称',
    width:140,
    ellipsis:true,
    dataIndex: 'label',
  },
  {
    title: '厂家简称',
    width:80,
    ellipsis:true,
    dataIndex: 'manufacturer',
    renderText: e => {
      return manufacturerOptionOnly()[Number(e)].text;
    }
  },
  {
    title: '报量层级',
    width:80,
    ellipsis:true,
    dataIndex: 'volumeLevel',
    renderText:(level)=>{
      if(level==='2'){
        return '医院'
      }
      return '科室'
    }
  },
  {
    title: '科室',
    dataIndex: 'name',
    width:300,
    render: (text, record:any,_, action) => {
      if(record.volumeLevel==='2'){
        return <></>
      }
      return <Select  mode="multiple" placeholder="请选择科室" defaultValue={record.depts}
      style={{ width: '100%' }}
      onChange={(value)=>{
        record.depts = value
      }}
      allowClear>
         {depts.map((item:any)=>{
           return <Option value={item.value} key={item.value}>{item.label}</Option>
         })}
      </Select>
    }
  },
  {
    title: '操作',
    valueType: 'option',
    width: 100,
    fixed: 'right',
    render: (text, record:any, _, action) => [
       <Popconfirm title='确定要删除该产品吗?' key='delete' onConfirm={() => {
          setPdata(pData.filter((item:any)=>item.value!=record.value))
       }
      }><a>删除</a></Popconfirm>
    ]}
   ]

  //  const onFileUpload=(info:any)=>{
  //   if (info.file.status !== 'uploading') {
  //   }
  //   if (info.file.status === 'done') {
  //     if(info.file.response.errorCode==='200'){
  //       message.success(`${info.file.name} 上传成功，后台正在处理...`);
  //       actionRef.current?.reloadAndRest?.();
  //       setShowImport(false);
  //     }else{
  //       message.error('上传失败: '+info.file.response.msg);
      
  //     }
  //   } else if (info.file.status === 'error') {
  //     message.error(`${info.file.name} 上传失败！`);
  //   }
  // }


const columns: ProColumns[] = [
  {
    title: '销售团队',
    dataIndex: 'name',
  },
  {
    title: '创建日期',
    valueType:'date',
    dataIndex: 'createDate',
  },
  {
    title: '创建人',
    dataIndex: 'createUser',
  },
  {
    title: '更新日期',
    valueType:'date',
    dataIndex: 'updateDate',
  },
  // {
  //   title: '更新人',
  //   dataIndex: 'updateUser',
  // },
  {
    title: '操作',
    valueType: 'option',
    width: 120,
    fixed: 'right',
    render: (text, record:any, _, action) => [
      <a key='detail' onClick={async () => {
         var val = await getDetailsByTeamId({teamId:record.id})
         setPdata(val.data.teamProductLines.map((item:any)=>{
            return {manufacturer:item.manufacturer,volumeLevel:item.volumeLevel,value:item.id,label:item.name,depts:item.teamHospitalDepartments.map((subItem:any)=>subItem.id)}
         }))
         val = await lineList({pageSize:100})
         setProductLines(val.data.map((item:any)=>{
           return {label:item.name,value:item.id,volumeLevel:item.volumeLevel,manufacturer:item.manufacturer}
         }))
         val = await deptList({})
         setDepts(val.data.map((item:any)=>{
          return {label:item.name,value:item.id}
        }))
         setProductLine(undefined)
         setDetail(record)
         setShowAuth(true)
       }}>修改</a>,
      //  <a key='detail' onClick={async () => {
      //    setDetail(record)
      //    setShowCreate(true)
      //  }}>修改</a>,
       <Popconfirm title='确定要删除吗?' key='delete' onConfirm={() => handleDelete(record.id)}><a>删除</a></Popconfirm>
    ]}
   ]
   const handleDelete = async(id:string) => {
        var val = await deleteTeam({
          id: id,
        });

       if (val.errorCode === '200') {
           message.success('删除成功')
           actionRef.current?.reloadAndRest?.()
       } else {
          message.error(val.errorMessage)
       }
   };


return (<PageContainer>
    <ProTable actionRef={actionRef} headerTitle='列表' pagination={{pageSizeOptions: ['20', '100', '500']}}
        request={(params, sorter, filter) => teamList({ ...params,filter})} columns={columns} rowKey='id' toolbar={{settings: []}}
       search={{labelWidth: 120}} toolBarRender={() => [<Button type='primary' key='primary' onClick={async() => {
        //  setShowCreate(true)
         setDetail(undefined)
         setPdata([])
          var val = await lineList({})
         setProductLines(val.data.map((item:any)=>{
           return {label:item.name,value:item.id}
         }))
         val = await deptList({})
         setDepts(val.data.map((item:any)=>{
          return {label:item.name,value:item.id}
        }))
         setProductLine(undefined)
         setShowAuth(true)
        }}>新增</Button>]}
   />
    <DrawerForm title={detail ? '编辑' : '新增'} onVisibleChange={setShowAuth} visible={showAuth} drawerProps={{forceRender: true,destroyOnClose: true}} 
  onFinish={async (values: any) => {

    var val = undefined
    values.lines = undefined
    if (detail) {
      values.id = detail.id;
      val = await updateTeam(values);
      var param = {teamId:detail.id,productLines:pData.map((item:any)=>{
        return {lineId:item.value,depts:item.depts}
      })}
      var val = await authTeam(param)
      if (val.errorCode === '200') {
          message.success('授权成功')
          actionRef?.current?.reloadAndRest?.()
          return true
      } else {
          message.error(val.errorMessage)
          return false
      }
    } else {
      val = await saveTeam(values);
    }
    if (val.errorCode === '200') {
      actionRef?.current?.reloadAndRest?.()
      return true
    }else{
      message.error(val.errorMessage)
    }
  }}>
    <div style={{marginLeft:20}}>
     <ProFormText name='name' label='销售团队名称'  placeholder='请输入团队名称' width='md' initialValue={detail?.name} rules={[{required: true}]} />
    </div>

    {
      detail?<ProTable headerTitle='产品' dataSource={pData}  rowKey='value' columns={pColumns} pagination={false} search={false} toolbar={{settings:[]}}
      toolBarRender={()=>[  <Form.Item key='lines' style={{marginBottom:-24}}>
      <ProFormSelect  key='lines' name='lines' label='' allowClear={false} placeholder='请选择产品'   width='sm'
      fieldProps={{onSelect:(v,v2)=>{
          // console.log(v,v2)
          setProductLine(v2)
      }}}
      options={productLines} /></Form.Item>,<Button type='primary' onClick={()=>{
        if(!productLine){
          message.warning('请先选择产品')
          return
        }
        if(pData.filter((item:any)=>item.value===productLine.value).length>0){
          message.warning('该产品已存在')
          return;
        }
        setPdata([...pData,{depts:[],...productLine}])
      }}>添加产品</Button>]}
    ></ProTable>:<></>
    }
      

	  </DrawerForm>
    {/* <ModalForm
            title="产品线科室授权导入"
            onVisibleChange={v=>{
              setShowImport(v);
            }}
            modalProps={{
              destroyOnClose:true,
              forceRender:true
            }}
            visible={showImport}
            onFinish={async (values: any) => {
              console.log(values);
               return true;
            }}
         >
             <div style={{margin:'10px 0 20px 0'}}><a href="/xwyl/attach/line_dept.xlsx" download="产品线科室.xlsx"><Button type="primary"> <FileExcelOutlined />产品线科室模板下载</Button></a></div>
            <ProFormUploadDragger label="选择excel上传" name="file" action='/xwyl/team/teamImport' fieldProps={{name:'file',headers:{'authorization':sessionStorage.getItem('token') as string}}}  max={1} onChange={onFileUpload} />

         </ModalForm> */}
    
   </PageContainer>
)}